package com.yuan.fruitweb.controller;

import com.yuan.fruitweb.model.Fruit;
import com.yuan.fruitweb.service.FruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;

import java.util.List;
@Controller
/**
 * @author YuanYuemeng
 * @date 2020/11/26
 */
public class FruitController {
    private FruitService fruitService;
    @Autowired
    public void setFruitService(FruitService fruitService) {
        this.fruitService = fruitService;
    }

    @GetMapping("toFruitAdd")
    public String toAdd(){
        return "fruitAdd";
    }

    /**
     *
     * @param fruit 要接收参数，只需要告诉参数放置在哪个对象
     * @return
     */
    @GetMapping("/fruitAdd")
    public String add(Fruit fruit){
        boolean ret = fruitService.saveFruit(fruit);
        if (ret){
            return "redirect:fruitList";
//            resp.sendRedirect("fruitList");
        }else {
            return "fruitAdd";
//            req.getRequestDispatcher("fruitAdd.jsp").forward(req,resp);
        }
    }

    @GetMapping("/fruitDel")
    public String del(int id){
        fruitService.delFruitById(id);
        //木有错误
        return "redirect:fruitList";
    }

    @GetMapping("/fruitEdit")
    public String toEdit(int id, Model model){
        Fruit fruit = fruitService.findFruitById(id);
        model.addAttribute("fruit",fruit);
        //木有错误
        return "fruitEdit";
    }

    @PatchMapping("/fruitEdit")
    public String doEdit(Fruit fruit){
        boolean ret = fruitService.updateFruit(fruit);
        if(ret){
            return "redirect:fruitList";
        }else{
            return "fruitEdit";
        }
    }

    @GetMapping("/fruitList")
    public String findAll(Model model){
        List<Fruit> fruits = fruitService.findAllFruits();
        model.addAttribute("fruits",fruits);
        //让jsp去显示数据
        return "fruitList";

    }
}
